package homework;

import cn.tedu.jdbc.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 使用预编译SQL实现注册功能;
 * 1.用户输入:用户名、密码、昵称、年龄;
 * 2.返回结果:
 * 2.1 用户名被占用[SELECT id FROM userinfo WHERE username=?];
 * 2.2 注册成功[INSERT INTO userinfo(username,password,nickname,age) VALUES (?,?,?,?)];
 */
public class JDBCLogin {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();) {
            Scanner scan = new Scanner(System.in);


            System.out.println("请输入用户名：");
            String userName = scan.nextLine();
            String sql1 = "SELECT userName FROM userinfo WHERE userName=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, userName);

            System.out.println("请输入密码：");
            String passWord = scan.nextLine();
            System.out.println("请输入昵称：");
            String nickName = scan.nextLine();
            System.out.println("请输入年龄：");
            Integer age = scan.nextInt();
            String sql2 = "INSERT INTO userinfo( userName,passWord,nickName,age) VALUES(?,?,?,?)";
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps2.setString(1, userName);
            ps2.setString(2, passWord);
            ps2.setString(3, nickName);
            ps2.setString(4, String.valueOf(age));

            ResultSet resultSet = ps1.executeQuery();

            if (resultSet.next()) {
                System.out.println("用户名已占用!");
            } else {
                int i = ps2.executeUpdate();
                if (i == 0) {
                    System.out.println("注册失败！");
                } else {
                    System.out.println("注册成功！");
                }


            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
